function getDataTable(type, start, rows) {
    var url = "datatable." + type + "link";

    new Ajax.Request(url + "/" + start + "/" + rows, {
        method: "get",
        onLoading: function(){
            $("loading").innerHTML = "Loading....";
        },
        onSuccess: function(response) {
            var dataTable = response.responseJSON;
//            alert(response.responseText);
            removeTable("dataTable");
            createTableHead("dataTable", dataTable.content[0]);
            createTable("dataTable", dataTable);

            removePaginationLinks("pageNumbers");
            createPaginationLinks(type, start, rows, dataTable.totalLength);
        },
        onComplete: function(response){
            $("loading").innerHTML = "Done.";
        },
        onException: function(response) {
            alert("error: " + response.responseText);
        }
    });
}

function createPaginationLinks(type, start, rows, totalLength) {
    var pageNumbersDiv = document.getElementById("pageNumbers");
    var pageCount = totalLength / rows;
    for (var i = 0; i < pageCount; i++) {
        var link = document.createElement("a");
        link.innerHTML = i + " ";
        link.href="#";
        link.setAttribute("onclick",
            "getDataTable('" + type + "'," + (i * rows) + "," + rows + ")");
            
        pageNumbersDiv.appendChild(link);
    }
}

function createTableHead(tableId, header) {
    var thead = document.getElementById(tableId).getElementsByTagName("thead")[0];
    var row = document.createElement("tr");

    for (var key in header) {
        var cell = document.createElement("td");
        var textNode = document.createTextNode(key.toString());
        cell.appendChild(textNode);
        row.appendChild(cell);
    }

    thead.appendChild(row);

    document.getElementById("dataTable").appendChild(thead);
}

function createTable(tableId, dataTable) {
    var tbody = document.getElementById(tableId).getElementsByTagName("tbody")[0];
    for (var i = 0; i < dataTable.content.length; i++) {
        var record = dataTable.content[i];
        var row = document.createElement("tr");
        for (var key in record) {
            var cell = document.createElement("td");
            var textNode = document.createTextNode(record[key]);
            cell.appendChild(textNode);
            row.appendChild(cell);
        }

        tbody.appendChild(row);
    }
    
    document.getElementById("dataTable").appendChild(tbody);
}

function removeTable(tableId) {
    var thead = document.getElementById(tableId).getElementsByTagName("thead")[0];
    thead.innerHTML = "<tr />";
    var tbody = document.getElementById(tableId).getElementsByTagName("tbody")[0];
    tbody.innerHTML = "<tr />";
}

function removePaginationLinks(pageNumbersDivId) {
    var tbody = document.getElementById(pageNumbersDivId).innerHTML = "";
}